<?php

namespace core;

class webservice
{
    private $server;
    private $config;
    public function __construct($config = array())
    {
        $this->config = $config;
    }
    public function init()
    {
        $this->server = new swoole_server($this->config['host'], $this->config['port']);
        $this->server->set($this->config['parameters']);
        $this->server->on("start", function ($server) {
            echo 'Start: manager_pid:' . $server->manager_pid . ' master_pid:' . $server->master_pid . "\n\n\n";
        });
        $this->server->on('WorkerStart', function ($serv, $worker_id) {
            echo 'WorkerStart:' . $serv->worker_id . ' / ' . $serv->worker_pid . "\n";
        });
        $this->server->on('Receive', function ($serv, $fd, $from_id, $data) {
            $respData = $data . "\r\n\r\n" . $fd . "\r\n\r\n" . $from_id;

            //响应行
            $response = array(
                'HTTP/1.1 200',
            );
            //响应头
            $headers = array(
                'Server' => 'COREAPI',
                'Content-Type' => 'application/json;charset=utf8',
                'Content-Length' => strlen($respData),
            );
            foreach ($headers as $key => $val) {
                $response[] = $key . ':' . $val;
            }
            //空行
            $response[] = '';
            //响应体
            $response[] = $respData;

            $send_data = join("\r\n", $response);
            $serv->send($fd, $send_data);
        });

    }
    public function run()
    {
        $this->server->start();
    }
}
